<template>
  <el-input ref="input"
            v-model="input"
            :size="size"
            :style="style"
            :placeholder="placeholder"
            :disabled="disabled"
            clearable
            @keydown="isChange = true"
            @blur.stop.prevent="onblur"
            @clear="onTableRowClick({})">
    <template #append>
      <el-button :class="disabled?'el-button-disabled':''" @click="onclick" icon="Search"/>
    </template>
  </el-input>
  <div class="my-dialog">
    <el-dialog draggable
               v-model="open"
               :title="title"
               :before-close="handleClose"
               width="70%"
               destroy-on-close
               append-to-body>
      <el-row>
        <el-col :span="6" :xs="24" v-if="isShowLeft">
          <div ref="box" class="box">
            <div class="head-container">
              <el-input v-model="deptName"
                        placeholder="请输入部门名称"
                        clearable
                        prefix-icon="Search"
                        style="margin-bottom: 20px"/>
            </div>
            <div class="head-container flow-tree">
              <el-tree :data="arrChangeTreeFn(organizationList)"
                       :props="{ label: 'organizationName', children: 'children' }"
                       :expand-on-click-node="false"
                       :filter-node-method="filterNode"
                       :default-expanded-keys="openTreeKeys"
                       ref="deptTreeRef"
                       node-key="organizationCode"
                       highlight-current
                       @node-click="handleOrgNodeClick"/>
            </div>
          </div>
        </el-col>
        <el-col :span="isShowLeft?18:24" :xs="24" style="padding-left: 1rem;">
          <el-form ref="filterFrom" :model="listQuery" :inline="true" class="demo-form-inline">
            <el-form-item prop="name" label="用户姓名">
              <el-input v-model="listQuery.name"
                        placeholder="用户姓名"
                        style="width: 100%;"
                        @keyup.enter.native="handleFilter"/>
            </el-form-item>
            <el-form-item prop="username" label="用户账号">
              <el-input v-model="listQuery.username"
                        placeholder="用户账号"
                        style="width: 100%;"
                        @keyup.enter.native="handleFilter"/>
            </el-form-item>
            <el-form-item>
              <el-button v-waves type="success" @click="handleFilter">
                查询
              </el-button>
              <el-button v-waves icon="Refresh" @click="handleResetQuery">
                重置
              </el-button>
            </el-form-item>
          </el-form>
          <el-divider class="el-divider--horizontal-margin"/>
          <el-table ref="tab" :data="tableDialogData" v-loading="loading" border @row-click="onTableRowClick">
            <el-table-column align="center" label="用户姓名" prop="name" min-width="115px" sortable/>
            <el-table-column align="center" label="用户账号" prop="username" min-width="150px" sortable/>
            <el-table-column align="center" label="性别" prop="gender" min-width="60px" sortable show-overflow-tooltip>
              <template v-slot="{row}">
                <EnumTag :enum-list="getEnumList('UserGender')" :enum-key="row.gender"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="手机号码" prop="mobile" min-width="105px" sortable
                             show-overflow-tooltip/>
            <el-table-column align="center" label="身份证号" prop="idcard" min-width="105px" sortable
                             show-overflow-tooltip/>
          </el-table>
          <pagination :total="tableDialogTotal" :page="listQuery.pageNum" :limit="listQuery.pageSize" @pagination="getList" />
        </el-col>
      </el-row>
      <template #footer>
      <span class="dialog-footer">
        <el-button type="info" icon="Close" @click="open = false">关闭</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet} from '@/config/http'
import {arrChangeTreeFn, getEnumList, getListPageSize, svc} from "@/config/common";

export default {
  name: "selectUserOrg",
  mixins: [baseConfig],
  components: {},
  emits: ['update:modelValue', 'onchoose'],
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    params: {
      type: Object,
      Object() {
        return {}
      }
    },
    isShowLeft: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: ''
    },
    modelValue: {
      type: String
    },
    keyName: 'id',
    keyShow: 'name',
    size: {
      default: 'default'
    },
    style: {
      default: ''
    },
    title: {
      type: String
    }
  },

  data() {
    return {
      value: '',
      isChange: true,
      row: null,
      input: '',
      open: false,
      loading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      tableDialogData: [],
      tableDialogTotal: 0,
      tOpenTable: null,
      organizationList: [],
      orgLink: [],
      deptName: '',
      openTreeKeys: [],
    }
  },
  watch: {
    value() {
      console.debug('this.value---', this.value)
      this.$emit('update:modelValue', this.value)
    },
    modelValue(val) {
      console.debug('val of user', val)
      if (!val) {
        this.input = ''
        this.row = null
      } else {
        this.init()
      }
    },
    deptName(val) {
      this.$refs.deptTreeRef.filter(val)
    },
  },
  created() {
    this.init()
  },
  mounted() {
  },
  methods: {
    arrChangeTreeFn,
    getEnumList,
    init() {
      this.getDeptTree()
      // this.$refs.deptTreeRef.setCurrentKey()
      /** 查询部门下拉树结构 */
      doGet(svc, `/organization/page`, {pageSize: getListPageSize(), type: '0'}, false).then(res => {
        this.organizationList = res?.records
        //如果存在账号，测处理反显
        if (this.modelValue) {
          let params = {
            id: this.modelValue,
            pageNum: 1,
            pageSize: 10,
            sortField: 'id',
            sortType: 'desc',
            source: '',
            gender: ''
          }
          doGet(svc, '/user/page', params, false).then(res => {
            if (res && res?.records && res.records.length > 0) {
              let list = res.records
              this.onTableRowClick(list[0])
            }
          })
        }
      });
    },
    handleNodeClick(data) {
      this.listQuery.organizationId = data.id;
      this.handleFilter()
    },
    handleClose() {
      this.open = false
    },
    onclick() {
      if (this.disabled)
        return false
      this.listQuery.organizationId = ''
      this.listQuery = Object.assign(this.listQuery, this.params)
      this.open = true
      this.getList()
    },
    onblur() {
      this.isChange = false
      this.tOpenTable = setTimeout(() => {
        this.input = this.row && (this.keyShow && this.row[this.keyShow] || this.row[this.keyName]) || ''
      }, 300)
    },
    clearTOpenTable() {
      setTimeout(() => {
        this.$nextTick(() => {
          clearTimeout(this.tOpenTable)
          this.tOpenTable = null
        })
      })
    },
    getOrgName(list, organizationId) {
      const obj = list.find(org => {
        if (org.id === organizationId) {
          this.orgLink.push({
            id: org.id,
            organizationCode: org.organizationCode,
            organizationName: org.organizationName,
          })
          return true
        } else if (org?.children && org.children.length > 0 && this.getOrgName(org.children, organizationId)) {
          this.orgLink.push({
            id: org.id,
            organizationCode: org.organizationCode,
            organizationName: org.organizationName,
          })
          return true
        } else {
          return false
        }
      })
      return !!obj;
    },
    onTableRowClick(row, column, event) {
      console.debug('row', row)
      console.debug('column', column)
      console.debug('event', event)
      this.clearTOpenTable()
      this.isChange = false
      this.row = row
      this.input = this.row && (this.keyShow && this.row[this.keyShow] || this.row[this.keyName]) || ''
      this.$emit('update:modelValue', row[this.keyName])
      console.debug(' this.input', this.input)
      this.orgLink = []
      this.getOrgName(arrChangeTreeFn(this.organizationList), row.organizationId)
      this.$emit('onchoose', row, this.orgLink)
      this.open = false
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleResetQuery() {
      this.$refs.filterFrom.resetFields()
    },
    getList() {
      this.loading = true
      doGet(svc, '/user/page', this.listQuery).then(res => {
        if (res && res?.records && res?.records.length > 0) {
          this.tableDialogData = res.records
          this.tableDialogTotal = parseInt(res?.total)
        } else {
          this.tableDialogData = []
          this.tableDialogTotal = 0
        }
        this.loading = false
      })
    },
    /** 通过条件过滤节点  */
    filterNode(value, data) {
      if (!value)
        return true;
      return data.organizationName.indexOf(value) !== -1;
    },
    /** 节点单击事件 */
    handleOrgNodeClick(data) {
      this.handleNodeClick(data)
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      doGet(svc, `/organization/page`, {pageSize: getListPageSize(), type: this.type}, false).then(res => {
        this.organizationList = res?.records
        this.openTreeKeys = []//[res?.records['organizationCode']]
      });
    },
  }
}
</script>

<style scoped lang="scss">
.el-button-disabled {
  cursor: no-drop;
}

.my-dialog {
  :deep(.pagination-container) {
    margin-top: 0;
  }

  :deep(.el-dialog__body) {
    padding-top: 0;
    padding-bottom: 10px;
  }
}

.box {
  //display: inline-grid;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
<style lang="scss">
.flow-tree {
  //--boxheight: 100px;
  .el-tree {
    width: 100%;
    //height: calc(100vh - 280px);
    //height: var(--boxheight);
    //height: 100%;
    overflow: auto;
  }

  .el-tree > .el-tree-node {
    display: inline-block;
    min-width: 100%;
  }
}
</style>
